﻿$(function () {
 Show()
    
})
	    //显示采购信息
	    function Show() {
    	        layui.use(function () {
                    var table = layui.table;
                    // 点击导出按钮
                    document.getElementById('exportBtnPurch').addEventListener('click', function () {
                        var checkStatus = table.checkStatus('Purchtable');  // 获取当前表格的选中状态
                        var selecteIds = checkStatus.data;  // 获取选中的数据

                        if (selecteIds.length === 0) {
                            alert('请先选择要导出的数据!');
                            return;
                        }

                        // 只有当选中数据不为空时才继续执行
                        var filteredData = selecteIds.map(function (item) {
                            // 创建一个新对象，只包含您想要的属性
                            return {
                                '采购Id': item.purchaseID,
                                '采购编号': item.purchaseCode,
                                '采购原料编号': item.ingredientnumber,
                                '采购原料名称': item.ingredientName,
                                '采购原料数量': item.purchaseNumber,
                                '申请日期': item.purchaseDate,
                                // 注意：这里可能是个拼写错误，应该是 '状态': item.purchaseStatus 而不是 '状态': item.purchaseSart
                                '状态': item.purchaseSart,
                            };
                        });

                        // 使用 XLSX 导出选中的数据
                        var wb = XLSX.utils.book_new();
                        var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
                        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
                        // 导出为 Excel 文件
                        XLSX.writeFile(wb, '采购列表.xlsx');
                    });
                 
               var PurchCode = $("#PurchCode").val();
               var PurchDate = $("#PurchDate").val();
               var PurchState = $("#PurchState").val();
       
               // 先进行表格的初始渲染
               table.render({
                       elem: '#Purchtable',  // 表格元素的选择器
                       page: {
                           limit: 5,
                           limits: [5, 8, 10]

        },
                      cols: [[
                              { type: 'checkbox', fixed: 'left' },
                              { field: 'purchaseCode', title: '采购编号' },
                              { field: 'ingredientnumber', title: '采购原料编号' },
                             
          { field: 'ingredientName', title: '采购原料名称' },
                              { field: 'purchaseNumber', title: '采购原料数量' },
                              {
            	                        field: 'purchaseDate', title: '申请日期',
            	                        templet: function(d) {
                                                  // 假设createdDate字段是一个日期字符串，格式为'YYYY-MM-DD HH:MM:SS'
                                                  // 截取前10位以获取日期部分.substring(0, 10)
                                                  var dateStr = d.purchaseDate;
                                                  // 返回包含日期的HTML字符串（这里可以简单地返回日期字符串，不需要额外的HTML标签）
                                                  return dateStr;
                        
                    }
	                    },
               	                    { field: 'purchaseSart', title: '状态' },
               	
	                    {
                     field: '', title: '操作', templet: function (d) {
                             if (d.purchaseSart === '待采购') {
                                     return '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs" onclick="showSupplierSelectionDialog(' + d.purchaseID + ')"><i class="layui-icon layui-icon-edit"></i>选择供应商</a> ' +
  '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs" onclick="showData1(' + d.purchaseID + ')"><i class="layui-icon layui-icon-edit"></i>查看</a> ' +
      '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.purchaseID + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
          '<a href="javascript:void(0);" class="layui-btn layui-btn-danger layui-btn-xs disabled" onclick="return false;"><i class="layui-icon layui-icon-delete"></i>删除（禁用）</a>';

                        } else if (d.purchaseSart === '已采购') {
                                               return '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs disabled"><i class="layui-icon layui-icon-edit"></i>选择供应商（禁用）</a> ' +
                                                       '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs" onclick="showData2(' + d.purchaseID + ')"><i class="layui-icon layui-icon-edit"></i>查看</a> ' +
                                                           '<a href="javascript:void(0);" class="layui-btn layui-btn-edit layui-btn-xs disabled" onclick="return false;"><i class="layui-icon layui-icon-edit"></i>编辑（禁用）</a> ' +
                                                               '<a href="javascript:void(0);" class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.purchaseID + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                           
                        }
                        
                    }
                }
]],
            	                // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
         data: []
     });

         // 创建表格实例
         $.ajax({
                url: "../Purch/PurchsList",
                type: "get",
                data: {
                    PageIndex: 1,
                    PageSize: 100,
                    token: "",
	                    PurchaseCode: PurchCode,
	                    PurchaseDate: PurchDate,
	                    PurchaseSart: PurchState
    },

    success: function (data) {
                data = JSON.parse(data);
                console.log(data.data.list);
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('Purchtable', {
                        page: {
                            limit: 5,
                            limits: [5, 8, 10]

        },
                                    data: data.data.list
                });

},
            error: function () {
                    console.log("请求失败");

}
	            });

	        });

	    }
	    // 单删数据的函数
	window.deleteData = function (purchaseID) {
     layer.confirm('确定要删除该条数据吗？', function () {
             $.ajax({
    	                type: "post",
    	                url: "../Purch/PurchDelete",  // 替换为实际的后台删除数据接口地址
    	                data: { PurchaseID: purchaseID, token: localStorage.getItem("token") },
    	                success: function (res) {
                        console.log(res)
                        var res = JSON.parse(res)
                        if (res.code == 1) {
    	                        layer.alert("删除成功");
                                           Show();  // 重新加载数据，刷新表格显示
                    
                } else {
                                         layer.alert("删除失败");
                   
                   
                }
                
            },
                   error: function () {
                           layer.msg('删除失败，请稍后重试', {
                                   time: 2000,
                                   icon: 2

                });
                
            }
        });


});
	    };
	    //编辑跳转
	window.editData = function (purchaseID) {
        localStorage['purchaseID'] = purchaseID;
    
        //localStorage.setItem("purchaseID", purchaseID)
        //console.log(localStorage.getItem("purchaseID"))
        location.href = '/Purch/UpdatePurch';
    
}

   //查看详情跳转（待采购）
 window.showData1 = function showData1(processRouteId) {
     localStorage.setItem("purchaseID", processRouteId)
	        console.log(localStorage.getItem("checkId"))
     location.href = '/Purch/DailyPurch';

}
//查看详情跳转（已采购）
window.showData2 = function showData2(processRouteId) {
    localStorage.setItem("purchaseID", processRouteId)
    console.log(localStorage.getItem("checkId"))
    location.href = '/Purch/YiPurch';

}
//选择供应商跳转
window.showSupplierSelectionDialog = function showSupplierSelectionDialog(processRouteId) {
    localStorage.setItem("checkId", processRouteId)
    console.log(localStorage.getItem("checkId"))
    location.href = '/Purch/ListSup';

}

////反填

//$(function () {
//    fantian1();

//})
////反填原料质检信息消息
//function fantian1() {
//    // 发送AJAX请求获取数据
//    console.log(localStorage.getItem("rawMaterialQualityId"))
//    $.ajax({
//        type: "get",
//        url: "/Quality/RawGetid",
//        data: {
//            id: localStorage.getItem("rawMaterialQualityId"),
//            token: localStorage.getItem("token")
//        },
//        success: function (res) {
//            var ter = JSON.parse(res)
//            console.log(ter.data)

//            $(ter.data).each(function () {
//                $('#QualityNumber').val(this.qualityNumber);
//                $('#QualityName').val(this.qualityName);
//                $('#QualityTime').val(this.qualityTime);
//                $('#Qualityer').val(this.qualityer);
//                $('#Supplier').val(this.supplier);
//                $('#MaterialNumber').val(this.materialNumber);
//                $('#MaterialName').val(this.materialName);
//                $('#Unit').val(this.unit);
//                $('#SpecificationsModel').val(this.specificationsModel);
//                $('#batchNumber').val(this.batchNumber);
//                $('#Size').val(this.size);
//                $('#QualityType').val(this.qualityType);
//                $('#QualityScheme').val(this.qualityScheme);
//                $("[name='QualityS'][value='" + this.qualityS + "']").prop("checked", true);

//            })

//        },

//    });


//}